package com.dcjt.firehotcarpad.utils

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.util.SparseArray
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.amap.api.location.AMapLocation
import com.amap.api.maps.AMap
import com.amap.api.maps.model.*
import com.amap.api.navi.view.RouteOverLay
import com.aries.library.fast.manager.LoggerManager
import com.aries.library.fast.util.FastStackUtil
import com.dcjt.firecommand.manager.MapDataRec
import com.dcjt.firehotcarpad.R
import com.dcjt.firehotcarpad.R2.id.position
import com.dcjt.firehotcarpad.entity.BiaohuiConfigEntity
import com.dcjt.firehotcarpad.entity.BiaohuiEntity
import com.dcjt.firehotcarpad.fragment.DisasterListInfoEntity
import com.dcjt.firehotcarpad.fragment.WaterSourceEntity
import com.google.gson.Gson


/**
 * Created by cj on 2021/2/23.
 * Email:codesexy@163.com
 * Function:
 * desc:
 */
object MapUtils {


    fun createMapMarkerOption(latLng: LatLng?, type: LocationType): MarkerOptions {
        return MarkerOptions().apply {
            position(latLng)
            icon(
                BitmapDescriptorFactory.fromBitmap(
                    BitmapFactory
                        .decodeResource(
                            FastStackUtil.getInstance().current.resources,
                            getIconId(type)
                        )
                )
            )
        }
    }
    fun viewToBitmap(view: View): Bitmap {
        view.measure(
            View.MeasureSpec.makeMeasureSpec(
                0,
                View.MeasureSpec.UNSPECIFIED
            ),
            View.MeasureSpec.makeMeasureSpec(
                0,
                View.MeasureSpec.UNSPECIFIED
            )
        )
        view.layout(0, 0, view.measuredWidth, view.measuredHeight)
        view.buildDrawingCache()
        return view.drawingCache
    }


    private fun getIconId(type: LocationType): Int {

        return when (type) {
            LocationType.LOCATION_CAMP -> R.drawable.icon_yq2
            LocationType.LOCATION_WATER -> R.drawable.icon_sy_zd2
            LocationType.LOCATION_COMBAT -> R.drawable.icon_zzw2
            LocationType.LOCATION_ASSEMBLY -> R.drawable.icon_jjd2
            LocationType.LOCATION_DISASTER -> MapDataRec.getCaseIconMap(type.flag)
            LocationType.LOCATION_AROUND_WATER -> R.drawable.icon_sy_zb2
            else -> R.drawable.icon_hz2
        }
    }

    /**
     * 获取PGS的状态信息
     */
    fun getGpsStatus(location: AMapLocation): String {
        return when (location.gpsAccuracyStatus) {
            AMapLocation.GPS_ACCURACY_BAD -> "信号差"
            AMapLocation.GPS_ACCURACY_GOOD -> "信号强"
            else -> {
                "状态未知"
            }
        }
    }

    fun getGpsBearing(location: AMapLocation): String {
        val bearing = location.bearing
        return when {
            bearing == 0f -> "正北"
            bearing < 90f -> "东北"
            bearing == 90f -> "正东"
            bearing < 180f -> "东南"
            bearing == 180f -> "正南"
            bearing < 270 -> "西南"
            bearing == 270f -> "正西"
            bearing < 360f -> "西北"
            else -> "正北"
        }
    }

    /**
     * 获取点击的规划线路
     */
    fun setClickPolyline(
        routeOverlays: SparseArray<RouteOverLay>,
        selectIndex: Int,
        polyline: Polyline
    ): Int {
        val latLngs = polyline.points
        if (latLngs.size == 0) {
            return -1
        }

        val latLng = latLngs[latLngs.size / 4]

        outer@ for (i in 0 until routeOverlays.size()) {
            val key = routeOverlays.keyAt(i)
            val naviLatLngs = routeOverlays[key].aMapNaviPath.coordList
            for (naviLatLng in naviLatLngs) {
                if (Math.abs(naviLatLng.latitude - latLng.latitude) <= 0.000001
                    && Math.abs(naviLatLng.longitude - latLng.longitude) <= 0.00001
                ) {
                    if (i == selectIndex) {   // 已经选过该路线 跳转下一条路线 可能重复路线
                        return i
                    }
                    for (j in 0 until routeOverlays.size()) {
                        if (i == j) {    //选中路线 不用画
                            continue
                        }
                        val key2 = routeOverlays.keyAt(j)
                        routeOverlays[key2].setTransparency(0.4f)
                        routeOverlays[key2].setZindex(0)
                    }
                    routeOverlays[key].setTransparency(1.0f)
                    /**把用户选择的那条路的权值弄高，使路线高亮显示的同时，重合路段不会变的透明 */
                    routeOverlays[key].setZindex(1)
                    return i
                }
            }
        }
        return -1
    }


    /**
     * 水源上图
     */
    fun addWaterSourceOnMap(
        points: List<WaterSourceEntity>,
        aMap: AMap,
        waterSourceMarkers: MutableList<Marker>
    ) {
        points.forEach {
            try {
//                val latLng = LatLng(it.gisY!!.toDouble(), it.gisX!!.toDouble())
                var latLng = Converter.toGCJ02Point_latlon(
                    it.gisY!!.toDouble(),
                    it.gisX!!.toDouble()
                )
                val options = createMapMarkerOption(latLng, LocationType.LOCATION_AROUND_WATER)
                val marker = aMap.addMarker(options).apply { `object` = it }
                marker.isVisible = true
                waterSourceMarkers.add(marker)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }


    /**
     * 标绘上图
     */
    fun addBiaohuiOnMap(
        list: List<BiaohuiEntity>,
        aMap: AMap,
        biaohuiMarkers: MutableList<Marker>,
        biaohuiPolygon: MutableList<Polygon>,
        biaohuiCircle: MutableList<Circle>,
        biaohuiPolyline: MutableList<Polyline>
    ) {
        list.forEach { it ->
            if (it.bhdxlxdm.isNullOrEmpty()) return@forEach
            if (StringUtils.isEmpty(it.bhzbs))  return@forEach

            var config = Gson().fromJson(it.bhys, BiaohuiConfigEntity::class.java)

            when {
                //文字标注
                it.bhdxlxdm!!.toInt()!! == 100501 || it.bhdxlxdm!!.toInt()!! == 200100 || it.bhdxlxdm!!.toInt()!! == 200200 || it.bhdxlxdm!!.toInt()!! == 200300 || it.bhdxlxdm!!.toInt()!! <100200 ->
                {
                    //点
                    val view =
                        View.inflate(FastStackUtil.getInstance().current, R.layout.layout_point, null)
                    val text_ponit =
                        view.findViewById<View>(R.id.text_ponit) as TextView
                    val icon_ponit =
                        view.findViewById<View>(R.id.icon_ponit) as ImageView
                    if (it.bhdxlxdm!!.toInt()!! == 100501){
                        //文字标注
                        icon_ponit.visibility = View.GONE
                    } else {
                        icon_ponit.visibility = View.VISIBLE
                        icon_ponit.setImageResource(FileUtils.getImgResourceForName(config.imgNo))
                    }
                    text_ponit.text = it.mc
                    val bitmap: Bitmap = viewToBitmap(view)

                      var marker =   aMap.addMarker(
                            MarkerOptions()
                                .icon(BitmapDescriptorFactory.fromBitmap(bitmap))
                                .position(getPointLatLng(it))
                                .title("organization${it.bhdxlxdm!!}")
                                .draggable(false)
                        )
                    biaohuiMarkers.add(marker)


                }
                it.bhdxlxdm!!.toInt()!! <100300 -> {
                    //线
                    var str = ""
                    if (it.bhzbs?.startsWith("[[")!!){
                        str = it.bhzbs?.substring(2, it.bhzbs?.length!! - 2)!!

                    } else if (it.bhzbs?.startsWith("[")!!){
                        str = it.bhzbs?.substring(1, it.bhzbs?.length!! - 1)!!

                    }
                    var arrayList = str!!.split("],[")
                    if (arrayList.isNotEmpty()) {
                        val latLngs= mutableListOf<LatLng>()
                        arrayList.forEach {
                           var arrayXY =  it.split(",")
                            //转坐标
                            latLngs.add( Converter.toGCJ02Point_latlon(
                                StringUtils.getStringNoKuohao(arrayXY[1]).toDouble(),
                                StringUtils.getStringNoKuohao(arrayXY[0]).toDouble()
                            ))

                        }
                        var polyline = aMap.addPolyline(
                            PolylineOptions().addAll(latLngs).width(config.lineWidth!!.toFloat())
                                .color(Color.parseColor(config.lineColor))
                        )
                        biaohuiPolyline.add(polyline)
                    }
                }
                it.bhdxlxdm!!.toInt()!! == 100301 ->{
                    //圆
                    var str = ""
                    if (it.bhzbs?.startsWith("[[")!!){
                        str = it.bhzbs?.substring(2, it.bhzbs?.length!! - 2)!!

                    } else if (it.bhzbs?.startsWith("[")!!){
                        str = it.bhzbs?.substring(1, it.bhzbs?.length!! - 1)!!
                    }
                    var arrayXY = str!!.split(",")
                    if (arrayXY.size<3){
                        return@forEach
                    }
                    if (arrayXY.isNotEmpty()) {
                        //转坐标
                        var latlng =  Converter.toGCJ02Point_latlon(
                            StringUtils.getStringNoKuohao(arrayXY[1]).toDouble(),
                            StringUtils.getStringNoKuohao(arrayXY[0]).toDouble()
                        )

                       var circle = aMap.addCircle(
                            CircleOptions().center(latlng).radius( arrayXY[2].toDouble())
                                .fillColor(Color.parseColor(config.fillColor))
                                .strokeColor(Color.parseColor(config.lineColor)).strokeWidth(config.lineWidth!!.toFloat())
                        )
                        biaohuiCircle.add(circle)
                    }
                }
                it.bhdxlxdm!!.toInt()!! <100400 -> {
                    //面
                    var str = it.bhzbs?.substring(2, it.bhzbs?.length!! - 2)
                    addBiaohuiPolygon(str, aMap, config, biaohuiPolygon)
                }
                it.bhdxlxdm!!.toInt()!! == 100405 -> {
                    //多箭头  数据后面多了一个  字符
                    var str = it.bhzbs?.substring(1, it.bhzbs?.length!! - 2)
                    // 进行| 分割出多个箭头
                    var array1 =str!!.split("|")
                    if (array1.isNotEmpty()) {
                        array1.forEach {
                            if (it.isNullOrEmpty()){
                                return@forEach
                            }
                            addBiaohuiPolygon(it, aMap, config, biaohuiPolygon)
                        }
                    }
                }
                it.bhdxlxdm!!.toInt()!! == 100406 -> {
                    //折线箭头
                    var str = it.bhzbs?.substring(2, it.bhzbs?.length!! - 2)
                    var arrayList = str!!.split("],[")

                    if (arrayList.isNotEmpty()) {
                        val latLngs= mutableListOf<LatLng>()
                        arrayList.forEach {
                            var arrayXY =  it.split(",")
                            //转坐标
                            latLngs.add( Converter.toGCJ02Point_latlon(
                                StringUtils.getStringNoKuohao(arrayXY[1]).toDouble(),
                                StringUtils.getStringNoKuohao(arrayXY[0]).toDouble()
                            ))
                        }

                        var polyline = aMap.addPolyline(
                            PolylineOptions().addAll(latLngs).width(config.lineWidth!!.toFloat())
                                .color(Color.parseColor(config.lineColor))
                        )
                        biaohuiPolyline.add(polyline)
                    }

                }
                it.bhdxlxdm!!.toInt()!! == 100402 -> {
                    //单箭头
                    var str = it.bhzbs?.substring(1, it.bhzbs?.length!! - 1)
                    addBiaohuiPolygon(str, aMap, config, biaohuiPolygon)
                }

            }

        }
    }

    private fun addBiaohuiPolygon(
        str: String?,
        aMap: AMap,
        config: BiaohuiConfigEntity,
        biaohuiPolygon: MutableList<Polygon>
    ) {
        var array = str!!.split(",")
        if (array.isNotEmpty()) {
            //转坐标
            val latLngs = mutableListOf<LatLng>()
            for (i in array.indices) {
                if (i % 2 == 1) {
                    latLngs.add(
                        Converter.toGCJ02Point_latlon(
                            StringUtils.getStringNoKuohao(array[i]).toDouble(),
                            StringUtils.getStringNoKuohao(array[i - 1]).toDouble()
                        )
                    )
                }
            }
            var polygon = aMap.addPolygon(
                PolygonOptions().addAll(latLngs).strokeWidth(config.lineWidth!!.toFloat())
                    .strokeColor(Color.parseColor(config.lineColor))
                    .fillColor(Color.parseColor(config.fillColor))
            )
            biaohuiPolygon.add(polygon)
        }
    }

    /**
     * 获取点的坐标
     */
    private fun getPointLatLng(it: BiaohuiEntity): LatLng? {
        var str = ""
        if (it.bhzbs?.startsWith("[[")!!){
            str = it.bhzbs?.substring(2, it.bhzbs?.length!! - 2)!!

        } else if (it.bhzbs?.startsWith("[")!!){
            str = it.bhzbs?.substring(1, it.bhzbs?.length!! - 1)!!

        }
        var arrayXY = str!!.split(",")
        if (arrayXY.isNotEmpty()) {
            //转坐标
            return Converter.toGCJ02Point_latlon(
                StringUtils.getStringNoKuohao(arrayXY[1]).toDouble(),
                StringUtils.getStringNoKuohao(arrayXY[0]).toDouble()
            )
        }
        return null
    }

    /**
     * 警情上图
     */
    fun addDisasterOnMap(
        points: List<DisasterListInfoEntity>,
        aMap: AMap,
        disasterMarkers: MutableList<Marker>
    ) {
        points.forEach looper@ {
            try {
//                val latLng = LatLng(it.gisY!!.toDouble(), it.gisX!!.toDouble())
                if(StringUtils.isEmpty(it.gisY) ||StringUtils.isEmpty(it.gisY)  ){
                    return@looper
                }
                var latLng = Converter.toGCJ02Point_latlon(
                    it.gisY!!.toDouble(),
                    it.gisX!!.toDouble()
                )
                LocationType.LOCATION_DISASTER.flag = it.ajlx!!
                val options = createMapMarkerOption(latLng, LocationType.LOCATION_DISASTER)
                val marker = aMap.addMarker(options).apply { `object` = it }
                disasterMarkers.add(marker)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

}


enum class MarkerToMapType(var desc: String) {
    MARKER_ADD("添加marker"),
    MARKER_HINT("隐藏marker"),
    MARKER_SHOW("显示marker"),
    MARKER_REMOVE("删除marker"),
    MARKER_IMITATE_CLICK("模拟点击marker")
}

enum class LocationType(var desc: String, var flag: String) {
    LOCATION_CAMP("营区", "yq"),
    LOCATION_WATER("水源", "sy"),
    LOCATION_COMBAT("作战位", "zzw"),
    LOCATION_ASSEMBLY("集结点", "jjd"),
    LOCATION_DISASTER("灾情点", "zqd"),
    LOCATION_AROUND_WATER("周边水源", "zbsy"),
    UPLOAD_EMERFENCY("突发情况", "tfqk"),
    OUT("出动", "03"),
    ARRIVE("到场", "0302"),
    EFFLUENT("出水", "0303"),
    WATERSTOP("停水", "0304"),
    BACK("返队", "0305"),
    DAIMING("待命", "02"),
    XUNLIAN("训练", "04"),
    JIAYOU("加油", "05"),
    WORK("公务", "08")
}
